package com.forumWebAutoTest.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class AutoTestUtils {
    //创建驱动对象，方便代码复用
    public static ChromeDriver driver;
    //创建驱动对象
    public static ChromeDriver createDriver(){
        //无头模式
        ChromeOptions options = new ChromeOptions();
        options.addArguments("-headless");

        //驱动对象以及创建好了/没有创建
        if(driver == null){
            driver=new ChromeDriver(options);
            //创建隐式等待
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        }
        return driver;
    }

    public List<String> getTime(){
        //文件按照天的维度按文件夹进行保存
        //文件格式 20230212-123030毫秒
        SimpleDateFormat sim1=new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        SimpleDateFormat sim2=new SimpleDateFormat("yyyyMMdd");
        String filename = sim1.format(System.currentTimeMillis());
        String dirname = sim2.format(System.currentTimeMillis());
        List<String> list =new ArrayList<>();
        list.add(dirname);
        list.add(filename);
        return  list;
    }

    /**
     *获取屏幕截图，保存测试用例的结果
     */
    public void getScreenShot(String str) throws IOException {
        List<String> list = getTime();
        //dir+filename
        String filename="./src/test/java/com/forumWebAutoTest/"+list.get(0)+"/"+str+"_"+list.get(1)+".png";
        File srcfile=driver.getScreenshotAs(OutputType.FILE);
        //把屏幕截图生成的文件放到指定的路径
        FileUtils.copyFile(srcfile,new File(filename));
    }
}
